<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container :disabled="formDisabled">
      <!-- 主表单区域 -->
      <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
        <a-row>
          <a-col :span="8">
            <a-form-model-item label="出库记录单号" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="entryNumber">
              <a-input v-model="model.recordNumber" placeholder="保存自动生成" disabled></a-input>
            </a-form-model-item>
          </a-col>
          <!--
          <a-col :span="8">
            <a-form-model-item label="审批流程" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="approvalFlow">
              <j-dict-select-tag
                type="list"
                v-model="model.approvalFlow"
                dictCode="outbound_record_flow"
                placeholder="请选择审批流程" />
            </a-form-model-item>
          </a-col>
          -->
          <a-col :span="8">
            <a-form-model-item label="出库日期" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="outboundDate">
              <j-date placeholder="请选择出库日期" v-model="model.outboundDate" style="width: 100%" />
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="出库类型" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="outboundType">
              <a-select v-if="!formDisabled" v-model="model.outboundType" placeholder="请选择出库类型">
                <a-select-option :value="7">盘亏出库</a-select-option>
                <a-select-option :value="8">手动出库</a-select-option>
              </a-select>
              <j-dict-select-tag v-else v-model="model.outboundType" dictCode="ck_type" />
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="备注" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="remark">
              <a-input v-model="model.remark" rows="4" placeholder="请输入备注" />
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>
    </j-form-container>
    <!-- 子表单区域 -->
    <select-inventory-material-modal ref="selectInventoryMaterialModal" @confirm="selectMaterialConfirm" />
    <j-vxe-table
      keep-source
      ref="outboundRecordItem"
      :loading="outboundRecordItemTable.loading"
      :columns="outboundRecordItemTable.columns"
      :dataSource="outboundRecordItemTable.dataSource"
      :maxHeight="300"
      :disabled="formDisabled"
      :rowNumber="true"
      :rowSelection="!formDisabled"
      :toolbar="true"
      :toolbarConfig="{
        slots: ['prefix', 'suffix'],
        btn: formDisabled ? [] : ['remove', 'clearSelection'],
      }"
      @remove="handleDelete"
    >
      <template #toolbarPrefix>
        <a-button @click="handleOpenMaterialModal" v-if="!formDisabled" type="primary" icon="plus"> 选择物料 </a-button>
      </template>
    </j-vxe-table>
  </a-spin>
</template>

<script>
import { getAction, httpAction } from '@/api/manage'
import { JVxeTableModelMixin } from '@/mixins/JVxeTableModelMixin.js'
import { JVXETypes } from '@/components/jeecg/JVxeTable'
import { getRefPromise, VALIDATE_FAILED } from '@/components/jeecg/JVxeTable/utils/vxeUtils.js'
import { validateDuplicateValue } from '@/utils/util'
import JFormContainer from '@/components/jeecg/JFormContainer'
import SelectInventoryMaterialModal from '@comp/warehouse/SelectInventoryMaterialModal.vue'
import { definitionStartByDataId, isFirstInitiator } from '@views/flowable/api/definition'
import dayjs from 'dayjs'
import utils from '@/utils/utils'

export default {
  name: 'OutboundRecordForm',
  mixins: [JVxeTableModelMixin],
  components: {
    SelectInventoryMaterialModal,
    JFormContainer,
  },
  data() {
    return {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 7 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      },
      model: {
        outboundDate: dayjs().format('YYYY-MM-DD'),
      },
      // 新增时子表默认添加几行空数据
      addDefaultRowNum: 1,
      validatorRules: {
        outboundDate: [{ required: true, message: '请选择出库日期!' }],
        outboundType: [{ required: true, message: '请选择出库类型!' }],
      },
      refKeys: ['outboundRecordItem'],
      tableKeys: ['outboundRecordItem'],
      activeKey: 'outboundRecordItem',
      // 出库记录明细表
      outboundRecordItemTable: {
        loading: false,
        dataSource: [],
        columns: [
          {
            title: '客户物料编码',
            key: 'customerMaterialCode',
            type: JVXETypes.normal,
            minWidth: '110px',
          },
          {
            title: '物料编码',
            key: 'materialCode',
            type: JVXETypes.normal,
            minWidth: '110px',
          },
          {
            title: '物料名称',
            key: 'materialName',
            type: JVXETypes.normal,
            minWidth: '220px',
          },
          {
            title: '规格型号',
            key: 'specificationModel',
            type: JVXETypes.normal,
            width: '90px',
          },
          {
            title: '单位',
            key: 'unit_dictText',
            type: JVXETypes.normal,
            dictCode: 'ji_unit',
            width: '60px',
          },
          {
            title: '库存数量',
            key: 'quantity',
            type: JVXETypes.normal,
            width: '80px',
          },
          {
            title: '辅单位',
            key: 'secondaryUnit_dictText',
            type: JVXETypes.normal,
            dictCode: 'zl_unit',
            width: '70px',
          },
          {
            title: '辅数量',
            key: 'secondaryQuantity',
            type: JVXETypes.normal,
            width: '80px',
          },
          {
            title: '生产日期',
            key: 'productionDate',
            type: JVXETypes.normal,
            width: '100px',
          },
          {
            title: '限用日期',
            key: 'expirationDate',
            type: JVXETypes.normal,
            width: '100px',
          },
          {
            title: '批次号',
            key: 'batchNumber',
            type: JVXETypes.normal,
            minWidth: '100px',
          },
          {
            title: '物料批号',
            key: 'materialBatchNumber',
            type: JVXETypes.normal,
            minWidth: '150px',
          },
          {
            title: '储位',
            key: 'storageLocation_dictText',
            type: JVXETypes.normal,
            minWidth: '150px',
          },
          {
            title: '质检状态',
            key: 'qualityInspectionStatus_dictText',
            type: JVXETypes.normal,
            width: '80px',
          },
          {
            title: '通知出库数量',
            key: 'notifyOutboundQuantity',
            type: JVXETypes.input,
            width: '120px',
            placeholder: '请输入${title}',
            defaultValue: '',
            validateRules: [{ required: true, message: '${title}不能为空' }],
          },
        ],
      },
      url: {
        add: '/wms/outbound/outbound-record/add',
        edit: '/wms/outbound/outbound-record/edit',
        queryById: '/wms/outbound/outbound-record/queryById',
        outboundRecordItem: {
          list: '/wms/outbound/outbound-record/queryOutboundRecordItemByMainId',
        },
      },
    }
  },
  props: {
    //表单禁用
    disabled: {
      type: Boolean,
      default: false,
      required: false,
    },
    warehouseCode: {
      type: String,
    },
    customFormData: {
      type: Object,
      default: () => {
        return {}
      },
      required: false,
    },
  },
  computed: {
    formDisabled() {
      return this.disabled
    },
  },
  created() {
    if (!this.formDisabled) {
      this.model.warehouseCode = this.warehouseCode
    }
    // 审批进来显示业务数据
    if (this.customFormData.id != null) {
      this.model = this.customFormData
      //刷新子表数据
      this.editAfter()
    }
  },
  methods: {
    handleOpenMaterialModal() {
      this.$refs.selectInventoryMaterialModal.showModal({ warehouseCode: this.model.warehouseCode })
    },
    addBefore() {
      this.outboundRecordItemTable.dataSource = []
    },
    /** 调用完edit()方法之后会自动调用此方法 */
    editAfter() {
      this.$nextTick(() => {})
      // 加载子表数据
      if (this.model.id) {
        let params = { id: this.model.id }
        this.requestSubTableData(this.url.outboundRecordItem.list, params, this.outboundRecordItemTable)
      }
    },
    /** 整理成formData */
    classifyIntoFormData(allValues) {
      let main = Object.assign(this.model, allValues.formValue)
      return {
        ...main, // 展开
        outboundRecordItemList: allValues.tablesValue[0].tableData,
      }
    },
    validateError(msg) {
      this.$message.error(msg)
    },
    handleDelete({ deleteRows }) {
      this.outboundRecordItemTable.dataSource = this.outboundRecordItemTable.dataSource.filter(
        (row) => !deleteRows.some((item) => item.id === row.id)
      )
    },
    async handleSubmit() {
      const validate = await this.$refs.form.validate()
      if (!validate) {
        return
      }
      if (!this.outboundRecordItemTable.dataSource.length) {
        this.validateError('请选择物料')
        return
      }
      let count = 0;
      this.outboundRecordItemTable.dataSource.forEach((item) =>{
        if(utils.sub(item.quantity, item.notifyOutboundQuantity) < 0){
          count = count + 1;
          this.validateError(item.materialName + ': 库存数量不足')
        }
      })
      if(count > 0){
        return
      }
      const errMap = await this.$refs.outboundRecordItem.validateTable()
      if (errMap) {
        return
      }
      const formData = {
        ...this.model,
        outboundRecordItemList: this.outboundRecordItemTable.dataSource.map((item) => {
          return {
            ...item,
            id: null,
            createBy: null,
            createTime: null,
            updateBy: null,
            updateTime: null
          }
        }),
      }
      this.request(formData)
    },
    request(formData) {
      let url = this.url.add,
        method = 'post'
      if (this.model.id) {
        url = this.url.edit
        method = 'put'
      }
      this.confirmLoading = true
      httpAction(url, formData, method)
        .then((res) => {
          if (res.success) {
            if (!this.model.id) {
              this.model.dataId = res.message
              // this.applySubmit(this.model)
            }
            this.$message.success('保存成功')
            this.$emit('ok')
            this.close()
          } else {
            this.$message.warning(res.message)
          }
        })
        .finally(() => {
          this.confirmLoading = false
        })
    },
    applySubmit(record) {
      if (record.dataId && record.dataId.length < 1) {
        this.$message.error('审批时必须传入参数dataId')
        return
      }
      //对于自定义业务，判断是否是驳回或退回的第一个发起人节点
      isFirstInitiator(record.dataId, record).then((res) => {
        if (res.success && res.result) {
          // 只有第一次能自动申请
        } else {
          const params = Object.assign({ dataId: record.dataId }, record)
          definitionStartByDataId(record.dataId, 'outboundRecordService', params).then((res) => {
            if (res.success) {
              this.$message.success(res.message)
            } else {
              this.$message.error(res.message)
            }
            this.$emit('ok')
          })
        }
      })
    },
    selectMaterialConfirm(rows) {
      if (!rows || rows.length <= 0) {
        return
      }
      this.outboundRecordItemTable.dataSource.push(...rows)
    },
  },
}
</script>

<style scoped></style>
